package com.example.mynewsapp.fragment

import android.app.Activity
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.TextView.OnEditorActionListener
import android.widget.*
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.mynewsapp.R
import com.example.mynewsapp.activity.DetailNews
import com.example.mynewsapp.adapter.NewsAdapter
import com.example.mynewsapp.fragment.Fragment.country
import com.example.mynewsapp.fragment.Fragment.db
import com.example.mynewsapp.fragment.Fragment.mActivity
import com.example.mynewsapp.fragment.Fragment.modelArticle
import com.example.mynewsapp.fragment.Fragment.news_adapter
import com.example.mynewsapp.model.ArticaleModel
import com.example.mynewsapp.model.NewsItem
import com.example.mynewsapp.model.NewsModel
import com.example.mynewsapp.network.ApiInterface
import com.example.mynewsapp.network.Constants.API_KEY
import com.example.mynewsapp.network.Constants.BASE_NEWS_URL
import com.example.mynewsapp.network.HttpRequest
import com.example.mynewsapp.util.Utils
import kotlinx.android.synthetic.main.fragment_news.*
import kotlinx.android.synthetic.main.fragment_search.*
import kotlinx.android.synthetic.main.fragment_search.view.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class FragmentSearch : Fragment() {

    var keywords :String = ""

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_search, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        recycler_view_search.setLayoutManager(LinearLayoutManager(context))
        recycler_view_search.setHasFixedSize(true)
        recycler_view_search.hideShimmerAdapter()
        imageClear.setVisibility(View.GONE)
        linearNews.setVisibility(View.GONE)

        imageClear.setOnClickListener {
            etSearchView.getText().clear()
            modelArticle.clear()
            linearNews.setVisibility(View.GONE)
            imageClear.setVisibility(View.GONE)
        }

    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        search_title.setText(R.string.search)

        etSearchView.setOnEditorActionListener(OnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                keywords = etSearchView.getText().toString()
                if (keywords.isEmpty()) {
                    Toast.makeText(context, getString(R.string.searchTips), Toast.LENGTH_SHORT).show()
                } else {
                    generateDummyList()
                }
                val inputManager = v.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                inputManager.hideSoftInputFromWindow(v.windowToken, 0)
                return@OnEditorActionListener true
            }
            false
        })
    }

    private fun generateDummyList(){

        if (keywords == "") return

        val list = ArrayList<NewsItem>()

        country = Utils.getCountry()

        val apiInterface = HttpRequest.createApi(BASE_NEWS_URL).create(ApiInterface::class.java)
        val call = apiInterface.getNewsSearch(keywords, "id", API_KEY)
        call.enqueue(object : Callback<NewsModel> {
            override fun onResponse(call: Call<NewsModel>, response: Response<NewsModel>) {
                if (response.isSuccessful && response.body() != null) {
                    modelArticle = response.body()?.data as MutableList<ArticaleModel>
                    for (i in 0 until modelArticle.size) {

                        val drawable = modelArticle[i].urlToImage
                        val update = Utils.DateTimeHourAgo(modelArticle[i].publishedAt)
                        val country = modelArticle[i].source.name + if (modelArticle[i].author==null) "" else "-"+ modelArticle[i].author
                        val desc = modelArticle[i].title
                        val date = Utils.DateFormat(modelArticle[i].publishedAt)
                        val url = modelArticle[i].url

                        var like = "no"
                        val cursor = db!!.query("favorite", null, null, null, null, null, null)
                        while (cursor.moveToNext()) {
                            val url_db = cursor.getString(cursor.getColumnIndex("newsUrl"))
                            if (url_db == url) {
                                like = "yes"
                                break
                            }
                        }
                        cursor.close()

                        val item = NewsItem(drawable, update, country, desc, date, url, like)
                        list += item

                    }
                    onSetList(list)
                }
            }
            override fun onFailure(call: Call<NewsModel>, t: Throwable) {
                tips()
            }
        })
    }

    // 设置列表
    private fun onSetList(list: ArrayList<NewsItem>) {

        if (recycler_view_search==null)return

        recycler_view_search.layoutManager = LinearLayoutManager(context)
        news_adapter = NewsAdapter(list!!,context!!)
        recycler_view_search.adapter = news_adapter
        news_adapter!!.notifyDataSetChanged()
        recycler_view_search.hideShimmerAdapter()
        linearNews.visibility = View.VISIBLE
        imageClear.visibility = View.VISIBLE

        news_adapter?.mOnRecyclerViewItemClick = object :
            NewsAdapter.OnRecyclerViewItemClick {
            override fun OnItemClick(view: View?, content: NewsItem, position: Int) {
                val intent = Intent(context, DetailNews::class.java)

                ifNewsExist(content)
                addData(content)

                intent.putExtra(DetailNews.DETAIL_NEWS, content)
                startActivity(intent)
            }

            override fun OnLongClick(view: View?, t: NewsItem, position: Int) {
            }
        }
    }

    private fun addData (content: NewsItem) {
        if (content.url == "") return
        //创建存放数据的ContentValues对象
        val values = ContentValues()
        values.put("newsImage", content.image)
        values.put("newsUpdate", content.update)
        values.put("newsCountry", content.country)
        values.put("newsTitle", content.title)
        values.put("newsDate", content.date)
        values.put("newsUrl", content.url)
        values.put("newsLike", content.like)
        //数据库执行插入命令
        db!!.insert("history", null, values)

    }

    private fun ifNewsExist (content: NewsItem){

        if (content.url == "") return

        val cursor = db!!.query("history", null, null, null, null, null, null)
        while (cursor.moveToNext()) {
            val url = cursor.getString(cursor.getColumnIndex("newsUrl"))
            if (url == content.url) {
                db!!.delete("history","newsUrl=?", arrayOf(url))
                break
            }
        }
        cursor.close() // 关闭游标，释放资源
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        mActivity = context as Activity
    }

    private fun tips() {
        if (this.isAdded){
            Toast.makeText(mActivity, getString(R.string.loadFail), Toast.LENGTH_SHORT).show()
        }
    }

    private fun searchNothing () {
        if (this.isAdded){
            Toast.makeText(mActivity, getString(R.string.searchNothing), Toast.LENGTH_SHORT).show()
        }
    }

}

